<?php
namespace voxfa\command;

require_once dirname(__FILE__)."/commandProcessorException.php";
require_once dirname(__FILE__)."/commandProcessorInterface.php";

class CommandManager {
	
	static private $instance = null;
	
	static public function getInstance(){
		if(self::$instance == null)
			self::$instance = new CommandManager();
		return self::$instance;
	}
	
	public function run(Command $command){
		$this->validate($command);
		$this->doRun($command);
	}
	
	private function validate(Command $command){
		$processorClass = $command->getCommandProcessor();
		if(!class_exists($processorClass))
			throw new CommandProcessorException("$processorClass does not exist!");	
	
		$rf = new ReflectionClass($processorClass);
		
		if(!$rf->implementsInterface('commandProcessorInterface'))
			throw new CommandProcessorException("$processorClass not implements commandProcessorInterface");	
	}
	
	/**
	 * @return command\commandResponse
	 * @param command $command
	 */
	private function doRun(Command $command){
		$runnerClass = $command->getCommandProcessor();
		$runnerInstance = new $runnerClass();
		
		try {
			$runnerInstance->run($command->getCommand(),$command->getDatamap());
		}catch(\Exception $e){
			throw new CommandProcessorException($e->getMessage(),$e->getCode(),$e);
		}
	}
}